import random
import string
from io import BytesIO
from PIL import Image, ImageFont, ImageDraw

class ImageCode():
    def get_text(self):
        list=random.sample(string.ascii_letters+string.digits,4)
        print(list)
        return "".join(list)

    def rand_color(self):
        red = random.randint(0,255)
        green = random.randint(0,255)
        blue = random.randint(0,255)
        return red,green,blue

    def draw_lines(self,draw,num,width,height):
        for i in range(num):
            x1 = random.randint(0, width / 2)
            y1 = random.randint(0, height / 2)
            x2 = random.randint(0, width / 2)
            y2 = random.randint(height / 2,height)
            draw.line(((x1,y1,),(x2,y2)),fill="black",width=2)

    def draw_verify_code(self):
        code = self.get_text()
        # 设置图片的宽和高
        width,height=120,50
        im = Image.new("RGB",(width,height),"black")
        # im.show()
        font = ImageFont.truetype(font="C:\Windows\Fonts\Arial.ttf",size=40)
        draw = ImageDraw.Draw(im)
        # 绘制字符串
        for i in range(4):
            draw.text((random.randint(3, 10) + 15 * i, random.randint(3, 10))
                      ,text=code[i], fill=self.rand_color(), font=font)
        # 绘制干扰线
        self.draw_lines(draw,3,width,height)
        return im, code
    def get_code(self):
        image,code=self.draw_verify_code()
        buf = BytesIO()
        image.save(buf,"jpeg")
        imagm_b_string = buf.getvalue()
        return code,imagm_b_string

# image_code = ImageCode()
# image_code.draw_verify_code()














